<?php
/*
Plugin Name: CDIA Portfolio
Plugin URI: http://www.cdiabu.com
Description: Adds a <strong>Portfolio</strong> post type that allows for easy creation of web development portfolios.
Author: Mike Burns
Version: 1.0
Author URI: http://grady-etc.com/
*/

// Includes
require( 'inc/portfolio.php' );

// Plugin Constants

/** 
 * This constant allows you to switch between using the Options API or the Settings API
 * for storing plugin data.
 */
define( 'CDIA_PORT_USE_SETTINGS_API', false );

define( 'CDIA_PORT_PLUGIN_DIR', basename( dirname( __FILE__ ) ) );
define( 'CDIA_PORT_PLUGIN_NAME', basename( __FILE__ ) );
define( 'CDIA_PORT_PLUGIN_PATH', basename( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR . basename( __FILE__ ) );

// Settings option_name for wp_options table
define( 'CDIA_PORT_OPTIONS_NAME', '_cdia_portfolio_settings' );
define( 'CDIA_PORT_META_KEY', '_cdia_portfolio_details' );

// Activation/Deactivate hooks
register_activation_hook( __FILE__, 'cdia_port_on_activate' );
register_deactivation_hook ( __FILE__, 'cdia_port_on_deactivate' );

// WordPress hooks
add_action( 'init', 'cdia_port_init' );
add_action( 'admin_init', 'cdia_port_admin_init' );
add_action( 'admin_menu', 'cdia_port_admin_menu' );

add_action( 'add_meta_boxes', 'cdia_port_add_metabox', 10, 2 );
add_action( 'save_post', 'cdia_port_on_post_save', 1, 2 );


/**
 * Run on plugin activation
 */
function cdia_port_on_activate() {
	
	// Check current WP version
	if( version_compare( get_bloginfo( 'version' ), '3.1', '<' ) ) {
		
		// Deactivate plugin if WordPress version is less than 3.1
		deactivate_plugins( CDIA_PORT_PLUGIN_PATH );
		
	} else {
		
		// Call the init hook before flushing rewrite rules so that our
		// post type gets registered first
		cdia_port_init();

		// Flush rewrite rules (for custom post type rewrites)
		flush_rewrite_rules();
	}
	
}

/**
 * Run on plugin deactivation
 */
function cdia_port_on_deactivate() {

	// Always clean up rewrite rules on deactivation when using
	// custom post types or taxonomies
	flush_rewrite_rules();
}

/****************************** PLUGIN INITIALIZATION *******************************/

/**
 *  On plugin initialization (run for both back and front-end pages)
 */
function cdia_port_init() {
	
	// Add portfolio custom post type
	cdia_port_register_portfolio();

}

/**
 *  On admin initialization (ONLY run on wp-admin/ pages)
 */
function cdia_port_admin_init() {

	if( defined( 'CDIA_PORT_USE_SETTINGS_API' ) && CDIA_PORT_USE_SETTINGS_API ) {
		
		// Create settings page (utilizes Settings API)
		cdia_port_create_settings();
		
	}
	
}

/****************************** PORTFOLIO MENU *******************************/

/**
 *  Register portfolio settings menu item 
 */
function cdia_port_admin_menu() {

	// Add portfolio settings page
	add_options_page( 'Portfolio Settings', // HTML title value
		'Portfolio Settings', 		// Menu item name
		'manage_options',		// User capabilities required
		'cdia-portfolio-settings', 	// URL page value (?page=< ... >)
		'cdia_port_settings_page'	// Callback function for page display
		);
	
	// Add portfolio settings page
	add_options_page( 'WP Style Playground', // HTML title value
		'WP Style Playground', 		// Menu item name
		'edit_posts',			// User capabilities required
		'cdia-style-playground', 	// URL page value (?page=< ... >)
		'cdia_port_style_playground'	// Callback function for page display
		);
}

/**
 * Options page with examples of WordPress conventional styles for Admin interface 
 */
function cdia_port_style_playground() {
	include 'interface/wordpress-styles.php';
}

/****************************** PLUGIN SETTINGS *******************************/

/**
 *  Add plugin options page
 */
function cdia_port_settings_page() {

	// Make sure current user can access our settings page
	if( !current_user_can( 'manage_options' ) ) {

		// Keep out the bad guys
		wp_die( 'You do not have sufficient permissions to access this page.' );
		
	}	

	/**
	 * The CDIA_PORT_USE_SETTINGS_API is a constant defined at the top of the page that
	 * allows you to switch between using the lower level options API or the newer
	 * Settings API for the plugin settings page.
	 * 
	 * If it is set to true, most of the logic for creating/updating/deleting options
	 * is handled in the callback functions below SETTINGS API IMPLEMENTATION below.
	 */
	if( defined( 'CDIA_PORT_USE_SETTINGS_API' ) && CDIA_PORT_USE_SETTINGS_API ) {
		
		// Render interface
		include 'interface/portfolio-settings.php';
		
	} else {

		$default_settings = array( 'email' => 'mike@grady-etc.com', 'summary' => 'Brag about your portfolio here...' );

		// Check for POST data
		if( isset( $_POST['action'] ) && $_POST['action'] == 'update' ) {
			
			// Verify form nonce
			if( !wp_verify_nonce( $_POST['_wpnonce'], 'update-portfolio-settings' ) ) {

				// Keep out the bad guys
				wp_die( 'Cheatin, uh?' );
				
			} else {

				// Extract post data
				$portfolio_settings = isset( $_POST['cdia_port_settings'] ) ? $_POST['cdia_port_settings'] : $default_settings;

				$portfolio_settings['email'] = sanitize_email( $portfolio_settings['email'] );	
				$portfolio_settings['summary'] = trim( $portfolio_settings['summary'] );	
				
				// Update portfolio settings option
				update_option( CDIA_PORT_OPTIONS_NAME, $portfolio_settings );
			}
		} else {

			// Fetch portfolio settings option
			$portfolio_settings = get_option( CDIA_PORT_OPTIONS_NAME );

		}
		
		// Insert defaults if they don't exist
		$portfolio_settings = wp_parse_args( $portfolio_settings, $default_settings );
		
		// Convert arrays to variables
		extract( $portfolio_settings );
		
		// Render interface
		include 'interface/portfolio-options.php';
	}
	
}

/****************************** SETTINGS API IMPLEMENTATION *******************************/

/**
 *  Register plugin settings with the Settings API
 * 
 *  See this post for a good tutorial:
 * 	http://ottodestruct.com/blog/2009/wordpress-settings-api-tutorial/
 */
function cdia_port_create_settings() {

	// Register plugin settings
	register_setting( 'cdia_port_settings',	// Setting group name
		CDIA_PORT_OPTIONS_NAME, 	// wp_options option_name
		'cdia_port_validate_settings'	// Callback function for validation
		);

	// Settings API setup
	add_settings_section( 'cdia_port_main', // An HTML ID tag for the section
		'Portfolio Settings',		// Section title text for display in <h3>
		'cdia_port_section_text',	// Callback function for section description
		'cdia-portfolio-settings'	// Settings page on which to show the section
		);
	
	add_settings_field( 'cdia_port_email', 	// An HTML ID tag for the section
		'Contact E-mail',		// Input label
		'cdia_port_setting_email', 	// Callback function for input field display
		'cdia-portfolio-settings', 	// Settings page on which to show the section
		'cdia_port_main' 		// Section ID tag for which this field belongs
		);
	
	add_settings_field( 'cdia_port_summary',// An HTML ID tag for the section
		'Portfolio Summary',		// Input label
		'cdia_port_setting_summary', 	// Callback function for input field display
		'cdia-portfolio-settings', 	// Settings page on which to show the section
		'cdia_port_main' 		// Section ID tag for which this field belongs
		);

}

/**
 *  Display settings page form heading
 */
function cdia_port_section_text() {
	
	echo '<p>Enter your settings below.</p>';
	
}

/**
 *  Display settings page email field
 */
function cdia_port_setting_email() {
	
	$options = get_option( CDIA_PORT_OPTIONS_NAME );
	$email = $options['email'];
	echo '<input id="email" name="'.CDIA_PORT_OPTIONS_NAME.'[email]" type="text" value="' . $email .'" />';

}

/**
 *  Display settings page email field
 */
function cdia_port_setting_summary() {
	
	$options = get_option( CDIA_PORT_OPTIONS_NAME );
	$summary = $options['summary'];
	echo '<textarea id="summary" name="'.CDIA_PORT_OPTIONS_NAME.'[summary]">' . $summary .'</textarea>';

}

/**
 *
 * @param array $input Form $_POST data pre database insertion
 * @return array $valid Form data sanitized and ready for database insertion
 */
function cdia_port_validate_settings( $input ) {
	$valid = array();
	$valid['email'] = sanitize_email( $input['email'] ); 	// Sanitize e-mail
	$valid['summary'] = trim( $input['summary'] );		// Trim whitespace from summary

	return $valid;

}

/***************************** CUSTOM META BOXES ******************************/

/**
 * Add our portfolio metabox to 'Portfolio' post type edit page
 * 
 * @param string $post_type The current post type being edited
 * @param StdObj $post A WordPress post object for the post currently being edited 
 */
function cdia_port_add_metabox( $post_type, $post ) {
	
	add_meta_box( 'cdia-port-meta',		// CSS ID of the <div> that wraps our metabox
		'Portfolio Details',		// Title of meta box (displayed at top of mb)
		'cdia_port_display_metabox',	// Callback for rendering metabox content
		'portfolio',			// Post types for meta box display
		'normal',			// Context - part of page where meta will show
		'high'				// Priority
		);
}

/**
 * Display our previously registered meta box on the 'Portfolio' post type edit page
 * 
 * @param StdObj $post A WordPress post object for the post currently being edited 
 */
function cdia_port_display_metabox( $post ) {
	
	// Retrieve metabox values from DB
	$port_meta_defaults = array(
	    'client_name' => 'Insert impressive client name here...',
	    'completion_year' => date( 'Y', time() ),
	    'cms' => 'WordPress',
	    'link' => 'http://'
	);

	// Fetch our serialized portfolio data from the database
	$port_meta = get_post_meta( $post->ID, CDIA_PORT_META_KEY, true );
	
	// Combine with defaults...
	$port_meta = wp_parse_args( $port_meta, $port_meta_defaults );

	// ...And convert to PHP variables
	extract( $port_meta );
	
	// Display the form
	include 'interface/portfolio-metabox.php';	
}

/**
 * Run on post save
 * 
 * @param int $post_id Post ID of the post being saved
 * @param StdObj $post WordPress post object for the post being saved
 */
function cdia_port_on_post_save( $post_id, $post ) {
	
	// Exit if attempting to save a revision
	if ($post->post_type == 'revision') {
		return;
	}

	// Incoming POST data...
	if( isset( $_POST['cdia_port_meta'] ) ) {

		// ...Extract POST values...
		$portfolio_details = $_POST['cdia_port_meta'];

		// ...Always sanitize before inserting in database...
		$portfolio_details['client_name'] = wp_strip_all_tags( $portfolio_details['client_name'] );
		$portfolio_details['completion_year'] = absint( $portfolio_details['completion_year'] );
		$portfolio_details['link'] = esc_url_raw( $portfolio_details['link'] );

		// ...and finally, update our post meta
		update_post_meta( $post_id, CDIA_PORT_META_KEY, $portfolio_details );
	}
}

?>